import React, {Component} from 'react';
import {WebView} from 'react-native-webview';
import router from '../../util/router'
import storage from '../../util/storage';
import BNavigationBar from '../../baseUI/b-navigation-bar/index'
import BSafeAreaViewPlugs from '../../baseUI/b-safe-area-view-plus/index'

/**
 * RN H5 通信 https://www.jianshu.com/p/44365ec64e4a
 */

export default class WebviewH5 extends Component {
  state = {
    token: ''
  }

  componentDidMount() {
    const params = this.props.route.params || {}
    this.props.navigation.setOptions({
      title: params.title
    })
    storage.getItem('userInfo').then(userInfo => {
      const token = userInfo ? userInfo.token : ''
      this.setState({ token })
    })
  }

  /**
   * 在h5中执行JS代码
   * @param {*} jsCode
   */
  injectJavaScript = (jsCode) => {
    const webView = this.refs['webview_ref'];
    webView.injectJavaScript(jsCode);
  };

  /**
   * 跳转到指定页面
   * @param {*} params 
   */
  goNativePage(params) {
    const {navigation} = this.props;
    switch (params.page) {
      // 跳转到通用h5容器
      case 'h5':
        router.goH5({
          navigation,
          url: params.url,
          title: params.title
        });
        break;
      case 'me':
        alert('me')
    }
  }

  /**
   * 监听来自h5的消息
   * @param {*} event
   */
  handleMessage = (event) => {
    const {navigation} = this.props;
    const message = event.nativeEvent;
    try {
      const payload = JSON.parse(message.data);
      let action = payload.action
      let params = payload.params;
      let callback = payload.callback;
      switch (action) {
        // 登录
        case 'login':
          if (params) {
            navigation.navigate('Login', {
              success: (userInfo) => {
                let jsCode = `window.${callback} && window.${callback}(${JSON.stringify(
                  userInfo,
                )});`;
                this.injectJavaScript(jsCode);
              },
            });
          }
          break;
        
        // 获取登录TOKEN
        case 'getToken':
          const userInfo = storage.getItem('userInfo')
          const token = userInfo ? userInfo.token : ''
          if (params) {
            let jsCode = `window.${callback} && window.${callback}(${JSON.stringify(
              token,
            )});`;
            this.injectJavaScript(jsCode);
          }
          break;

        // 页面跳转
        case 'goto':
          this.goNativePage(params)
          break;

        // 分享
        case 'share':
          alert('share');
      }
    } catch (e) {
      alert('调用APP方法参数错误！参数为：' + message.data);
    }
  };
}
